package thread;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author: Administrator
 * @Date: 2023/2/9 15:03
 * demo = new DLCDemo();
 * 不原子，分3步 --- #2  #3这两步可能发生重排序，将导致某个线程拿到不完整的对象，最终npe
 *                     //1分配内存
 *                     //2.初始化
 *                     //3.将引用赋值给变量
 *
 *
 */

public class DLCDemo {
   /*volatile*/ DLCDemo demo;
    String s = "n" + new String("j");

    public DLCDemo getInstance() {

        if (demo == null) {
            synchronized (DLCDemo.class) {
                if (demo == null) {
                    //不原子，分3步 --- #2  #3这两步可能发生重排序，将导致某个线程拿到不完整的对象，最终npe
                    //1分配内存
                    //2.初始化
                    //3.将引用赋值给变量

                    demo = new DLCDemo();
                }
            }
        }
        return demo;
    }


    public static void main(String[] args) {
        AtomicBoolean f = new AtomicBoolean(true);
        while (f.get()) {
            DLCDemo dlcDemo = new DLCDemo();
            Thread[] threads = new Thread[3];
            for (int i = 0; i < threads.length; i++) {
                threads[i] = new Thread(() -> {
                    DLCDemo instance = dlcDemo.getInstance();
                    if (instance.s == null) {
                        System.out.println("原则上执行不到");

                        f.set(false);
                    }
                });
            }
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }
        }


    }

}

